﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using Ant.ICommon.Utilities;
using Ant.Interface.Mef.Controller;

namespace Ant.Interface.Mef
{
    //    public delegate void CreateContainerHandler(ConventionBuilder conventionBuilder);

    /// <summary>
    /// 可用Mef控制器枚举。
    /// </summary>
    public enum MefControllerEnum
    {
        /// <summary>
        /// 默认。
        /// </summary>
        Default = 0,

        /// <summary>
        /// 主机的。
        /// </summary>
        Host = 1
    }

    /// <summary>
    /// Mef工厂。
    /// </summary>
    public class MefFactory
    {
        #region "Field"

        /// <summary>
        /// 存放Mef控制器且线程安全的字典表。
        /// </summary>
        private static readonly IDictionary<string, IMefController> _dictionary = new ConcurrentDictionary<string, IMefController>();

        #endregion "Field"

        #region "Property"

        /// <summary>
        /// 创建Mef控制器。
        /// </summary>
        /// <returns>Mef控制器。</returns>
        private static IMefController CreateMefController()
        {
            return Cast.GetInstance<IMefController>("Ant.Interface.Mef.Controller.MefController,Ant.Interface");
        }

        #endregion "Property"

        #region "Constructor"

        private MefFactory()
        {
        }

        #endregion "Constructor"

        #region "Public Method"

        /// <summary>
        /// 获取Mef控制器。
        /// </summary>
        /// <param name="mefControllerEnum">可用Mef控制器枚举。</param>
        /// <returns>Mef控制器。</returns>
        public static IMefController GetInstance(MefControllerEnum mefControllerEnum = MefControllerEnum.Default)
        {
            var key = mefControllerEnum.ToString();
            IMefController mefController;
            if (!_dictionary.TryGetValue(key, out mefController))
            {
                mefController = CreateMefController();
                _dictionary.Add(key, mefController);
            }
            return mefController;
        }

        #endregion "Public Method"
    }
}